﻿using System;
using System.Activities.Presentation.Model;
using System.Activities.Presentation.Services;
using System.Collections.Generic;
using System.Windows;

namespace Headsight.BPMN2WF.WF.Impl
{
    /// <summary>
    /// Currently: Collection of diversified <i>helper methods / stuff operating on <see cref="ModelItem"/></i>...
    /// </summary>
    public class ModelItemUtils
    {
        private readonly ModelItem _modelItem;
        private readonly ViewService _vSrv;

        public ModelItemUtils(ModelItem modelItem, ViewService viewService)
        {
            _modelItem = modelItem;
            _vSrv = viewService;
        }

        public ModelItem InnerItem
        {
            get { return _modelItem; }
        }

        private static ModelItem GetValue(ModelItem modelItem, String propertiesKey)
        {
            ModelItem result = null;
            ModelProperty mProp;

            if ((mProp = modelItem.Properties[propertiesKey]) != null)
            {
                result = mProp.Value;
            }

            return result;
        }

        public IList<ModelItem> ImmediateChilds
        {
            get
            {
                var result = new List<ModelItem>();

                Action<String> addIfExisting = x =>
                {
                    var mItem = GetValue(_modelItem, x);
                    if (mItem != null)
                    {
                        result.Add(mItem);
                    }
                };

                addIfExisting("Implementation");
                addIfExisting("StartNode");
                addIfExisting("Next");
                addIfExisting("True");
                addIfExisting("False");

                return result;                
            }
        }

        public FrameworkElement View
        {
            get
            {
                var action = GetValue(_modelItem, "Action");

                if (action != null && action.View != null)
                {
                    return (FrameworkElement) action.View;
                }

                return (FrameworkElement)_vSrv.GetView(_modelItem);
            }
        }
    }
}
